import {
	baseURL
} from "../utils/request.js"
import {
	ocrIdcard,
	aiBusinessLicense,
	ocrBankcard
} from "../api/join.js"
class UploadFile {
	constructor(ocrType='',isOcr=false) {

		// 原始属性定义
		this.config = {
			// fileListLen: 0, //上传文件个数
			status: '', //上传文件状态
			filelist: [], //已上传的文件列表
			ocrData: {}, //ocr识别后的数据
			halfRoadRoute: [],
			ocrType,
			isOcr
		}
	}

	// 新增图片
	async afterRead(event) {
		return new Promise(async(resolve, reject) => {
			let lists = [].concat(event.file);
			// this.config.fileListLen = this.config.filelist.length;
			this.config.filelist = lists.map(item => {
				return {
					...item,
					status: "uploading",
					message: "上传中",
				}
			})
			const uploadResults = await Promise.all(
				lists.map(async file => {
					const result = await this.uploadFilePromise(file.url);
					console.log(result);
					this.config.filelist = this.config.filelist.map((item, index) => {
						if (index == lists.indexOf(file)) {
							return {
								...item,
								status: "success",
								message: "",
								url: result.full_url,
							}

						}
						return item
					})
					if (this.config.isOcr) {
						this.config.ocrData = await this.distinguishOcr(result.full_url)
					}
				})
			)
			resolve({
				filelist: this.config.filelist, //已上传的文件列表
				ocrData: this.config.ocrData, //ocr识别后的数据
				halfRoadRoute: this.config.halfRoadRoute,
			})
		})

	}
	async uploadFilePromise(url) {
		var that = this
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: baseURL + `localSeller/common/upload`,
				filePath: url,
				name: 'file',
				header: {
					"ba-user-token": uni.getStorageSync("token") || ''
				},
				success: (res) => {
					let datainfo = JSON.parse(res.data);
					if (datainfo.code == 1) {
						that.config.halfRoadRoute = that.config.halfRoadRoute.concat(datainfo
							.data.url)
						resolve(JSON.parse(res.data).data);

					} else {
						that.config.fileList1 = []
						uni.$u.toast(datainfo.msg);
					}
				}
			});
		});
	}
	// OCR识别
	distinguishOcr(url) {
		return new Promise((resolve, reject) => {
			uni.showLoading({
				title: '加载中'
			});
			let data = {
				image: url
			};
			let request = ''
			if(this.config.ocrType == 'yyzh'){
				request = aiBusinessLicense
			}else if(this.config.ocrType == 'face'){
				request = ocrIdcard
			}else if(this.config.ocrType == 'yhkh'){
				request = ocrBankcard
			}
			request(data).then(res => {
				uni.hideLoading();
				if (res.code == 1) {
					resolve(res.data)
					// this.config.ocrData = res.data
				}
			})
		})


	}
}
export default UploadFile